/**
 * @description address router
 */
const router = require('koa-router')()
const {SuccessModel, ErrorModel}=require('../res-model/index')
const {createAddress,getAddressList,
  getAddressById,updateAddress}=require('../controller/address')
const  loginCheck=require('../middleware/loginCheck')
router.prefix('/api/user/address')
//创建收货地址
router.post('/',loginCheck,async(ctx,next)=>{
  const {username}=ctx.session.userInfo
  const data=ctx.request.body
  try{
    const newAddress=await createAddress(username,data)
    ctx.body=new SuccessModel(newAddress)
  }catch(e){
    console.error(e);
    ctx.body=new ErrorModel(-4,'创建售后地址失败')
  }
})
//获取收货地址列表
router.get('/',loginCheck,async (ctx,next)=>{
  const {username}=ctx.session.userInfo
  const list=await getAddressList(username)
  ctx.body=new SuccessModel(list)
})
//获取某个收货地址
router.get('/:id',loginCheck,async(ctx,next)=>{
  const id=ctx.params.id;//获取路由的动态参数
  const address=await getAddressById(id)
  ctx.body=new SuccessModel(address)
})
//更新某个收货地址
router.patch('/:id',loginCheck,async(ctx,next)=>{
  const {username}=ctx.session.userInfo
  console.log(username);
  const id=ctx.params.id //获取路由的动态参数
  const data=ctx.request.body || {} //前端传来的数据
  const newAddress=await updateAddress(id,username,data)
  ctx.body=new SuccessModel(newAddress)

})
module.exports = router